package com.mr.dao.common;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mr.dao.entity.BaseEntity;
import com.mr.dao.util.CriteriaUtil;

/**
 * @author Alex
 */
@Repository
public class CommonDao {
	@Autowired
	private SessionFactory sessionFactory;

	// ------------Several following methods are about loading object.

	@SuppressWarnings("unchecked")
	public <T extends BaseEntity> T load(Class<T> clazz, Serializable id) {
		return (T) getSession().get(clazz, id);
	}

	public <T extends BaseEntity> T load(Class<T> clazz, String name, Object value) {
		return load(clazz, new String[] { name }, new Object[] { value });
	}

	@SuppressWarnings("unchecked")
	public <T extends BaseEntity> T load(Class<T> clazz, String[] names, Object[] values) {
		Criteria criteria = CriteriaUtil.generateCriteria(getSession(), clazz, names, values);
		return criteria == null ? null : (T) criteria.uniqueResult();
	}

	// ------------Several following methods are about finding objects.

	@SuppressWarnings("unchecked")
	public <T extends BaseEntity> List<T> findAll(Class<T> clazz, String... orderProperties) {
		Criteria criteria = CriteriaUtil.create(getSession(), clazz);
		if (orderProperties != null) {
			for (String orderProperty : orderProperties) {
				criteria.addOrder(Order.asc(orderProperty));
			}
		}
		return criteria.list();
	}

	public <T extends BaseEntity> List<T> find(Class<T> clazz, String propertyName, Object propertyValue) {
		return find(clazz, new String[] { propertyName }, new Object[] { propertyValue });
	}

	@SuppressWarnings("unchecked")
	public <T extends BaseEntity> List<T> find(Class<T> clazz, String[] propertyNames, Object[] propertyValues) {
		Criteria criteria = CriteriaUtil.generateCriteria(getSession(), clazz, propertyNames, propertyValues);
		return criteria == null ? null : criteria.list();
	}

	public <T extends BaseEntity> Long count(Class<T> clazz, String[] propertyNames, Object[] propertyValues) {
		Criteria criteria = CriteriaUtil.generateCriteria(getSession(), clazz, propertyNames, propertyValues);
		return (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
	}

	public <T extends BaseEntity> Long count(Class<T> clazz) {
		return count(clazz, null, null);
	}

	// ------------Save method.

	public void save(Object entity) {
		getSession().saveOrUpdate(entity);
	}

	// ------------Delete method.

	public void delete(Object entity) {
		getSession().delete(entity);
	}

	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}
}
